import axios from 'axios'
import { ElMessage } from 'element-plus';

const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_API, // api 的 base_url
    timeout: 30000, // 30s默认超时
    withCredentials: false
})

// request拦截器
service.interceptors.request.use(
    config => {
        // 特殊请求延长超时
        if (config.url.includes('/export') || config.url.includes('/import')) {
            config.timeout = 300000; // 5分钟
        }
        // todo: 这里看看是否要带上headers？
        console.log('请求完整URL:', config.baseURL + config.url);
        console.log('请求方法:', config.method);
        console.log('请求头:', config.headers);
        console.log('请求参数:', config.params || config.data);
        return config
    },
    error => {
        // 错误处理
        console.error('请求发送失败:', error);
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        const {data, headers} = response;
        // todo: 是否要更新token
        if(data.code && data.code !==200){
            return handleBusinessError(data);
        }
        return response;
    }, error => {
        console.error('响应错误:', error.response);
        handleBusinessError(error)
    }
)

function handleBusinessError(response){
    const errorMap = {
        400: '请求参数错误',
        401: '认证失效，请重新登录',
        403: '权限不足',
        404: '资源不存在',
        405: '请求方法不支持',
        406: '数据格式错误',
        500: '服务器内部错误'
    }
    const message = errorMap[response.status] || `业务有误：${response.status}`;
    ElMessage.error(message);
}

/**
 * put方法，对应put请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {Object} header [请求头部]
 * @returns Promise
 */
export function put(url, params = {}, header) {
    return new Promise((resolve, reject) => {
        service({
            url,
            method: 'put',
            data: params,
            headers: header || {
                'Content-Type': 'application/json;charset=UTF-8'
            }
        }).then(response => {
            resolve(response.data)
        }).catch(error => {
            reject(error)
        })
    })
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {Object} header [请求头部]
 * @returns Promise
 */
export function post(url, params = {}, header) {
    return new Promise((resolve, reject) => {
        service({
            url,
            method: 'post',
            data: params,
            headers: header || {
                'Content-Type': 'application/json;charset=UTF-8'
            }
        }).then(response => {
            resolve(response.data)
        }).catch(error => {
            reject(error)
        })
    })
}

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {header} header
 * @returns Promise
 */
export function get(url, params = {}, header) {
    return new Promise((resolve, reject) => {
        service({
            url,
            method: 'get',
            params: params,
            headers: header || {
                'Content-Type': 'application/json;charset=UTF-8'
            }
        }).then(response => {
            debugger
            resolve(response.data)
        }).catch(error => {
            reject(error)
        })
    })
}

export default service
